<?php
/**
 * Created by PhpStorm.
 * User: lx
 * Date: 2020/1/3
 * Time: 13:52
 */
namespace app\command\controller;

use app\mtadminapi\controller\Base;
use app\mtadminapi\model\MtBhArea;
use think\cache\driver\Redis;
use think\Controller;
use app\command\controller\MyCurl;
use think\Session;
use think\Validate;
use app\util\ReturnCode;
use think\Db;

/**
 * 公共方法
 * Class Common
 * @package app\command\controller
 */
class Common extends Controller
{
    public $rule = [];
    public $msg = [];
    public function __construct(){
        parent::__construct();
    }
    /**
     * 接收数据验证
     * @param $data
     * @return string
     */
    public function VerifiString($rule,$msg,$postData){
        $validate = new Validate($rule,$msg);
        $result   = $validate->check($postData);
        if(!$result){
            return ["code"=>2,"msg"=>$validate->getError()];
        }
        return ['code'=>1];
    }

    /**
     * 文件上传
     * @return mixed
     */
    public function upload($path, $fileName, $size = 102400) {
        $path = '/upload/' .$path . date('Ymd', time()) . '/';
        $name = $_FILES[$fileName]['name'];
        $tmp_name = $_FILES[$fileName]['tmp_name'];
        $error = $_FILES[$fileName]['error'];
        //过滤错误
        if ($error) {
            switch ($error) {
                case 1:
                    $error_message = '您上传的文件超过了PHP.INI配置文件中UPLOAD_MAX-FILESIZE的大小';
                    break;
                case 2:
                    $error_message = '您上传的文件超过了PHP.INI配置文件中的post_max_size的大小';
                    break;
                case 3:
                    $error_message = '文件只被部分上传';
                    break;
                case 4:
                    $error_message = '文件不能为空';
                    break;
                default:
                    $error_message = '未知错误';
            }
            return $this->error(ReturnCode::FILE_SAVE_ERROR, $error_message);
        }
        $info = finfo_open(FILEINFO_MIME_TYPE);
        //第二步：将finfo资源和文件做比较
        $mime = finfo_file($info,$_FILES[$fileName]['tmp_name']);
        //第三步，比较是否合法
        $allow=array('image/jpeg','image/png','image/gif');    //允许的类别
        if(!in_array($mime,$allow)){
            return '只能上传'.implode(',',$allow).'格式';
        }
        //3、验证大小
        if($_FILES[$fileName]['size']>$size){
            return $this->error(ReturnCode::FILE_SAVE_ERROR, '文件大小不能超过'.number_format($size/1024,1).'K');
        }
        $arr_name = explode('.', $name);
        $hz = array_pop($arr_name);
        $new_name = md5(time() . uniqid()) . '.' . $hz;
        if (!file_exists($_SERVER['DOCUMENT_ROOT'] . $path)) {
            mkdir($_SERVER['DOCUMENT_ROOT'] . $path, 0755, true);
        }
        if (move_uploaded_file($tmp_name, $_SERVER['DOCUMENT_ROOT'] . $path . $new_name)) {
            return $this->success('上传成功',[
                'fileName' => $new_name,
                'fileUrl'  => $this->request->domain() . $path . $new_name
            ]);
        } else {
            return $this->error(ReturnCode::FILE_SAVE_ERROR, '文件上传失败');
        }
    }

    /**
     * 递归
     * @param $groupData
     * @param int $id
     */
    public function recursion($data,$parentID = 'parentID', $idName = 'id',$id = 0){
        //初始化儿子
        $child = [];
        //循环所有数据找$id的儿子
        foreach ($data as $key => $datum) {
            //找到儿子了
            if ($datum[$parentID] == $id) {
                //保存下来，然后继续找儿子的儿子
                $child[$datum[$idName]] = $datum;
                //先去掉自己，自己不可能是自己的儿孙
                unset($data[$key]);
                //递归找，并把找到的儿子放到一个child的字段中
                $child[$datum[$idName]]['child'] = $this->recursion($data,$parentID,$idName,$datum[$idName]);
            }
        }
        $child = array_merge($child);
        return $child;
    }

    public function generateTree($list, $pk = 'id', $pid = 'pid', $child = 'children', $root = 0){
        $tree     = array();
        $packData = array();
        foreach ($list as $data) {
            $packData[$data[$pk]] = $data;
        }
        foreach ($packData as $key => $val) {
            if ($val[$pid] == $root) {
                $tree[] = &$packData[$key];
            } else {
                $packData[$val[$pid]][$child][] = &$packData[$key];
            }
        }
        return $tree;
    }
    /**
     * 地区联动
     * @return array|\PDOStatement|string|\think\Collection
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\ModelNotFoundException
     * @throws \think\exception\DbException
     */
    public function chinaArea(){
        $areaID = $this->request->param("areaID");
        if(empty($areaID)){
            $areas = (new MtBhArea())->where("parentId",0)->select();
        }else{
            $areas = (new MtBhArea())->where("parentId",$areaID)->select();
        }
        return (new Base())->bindSuccess("请求成功",$areas);
    }
}